import axios from 'axios'
import router from './router'
import store from "@/store";
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' // 引入css样式文件
axios.defaults.timeout = 30000;
//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;
// 进度条的配置项：ease可以设置css3动画，如ease，linear；speed是进度条从开始到结束的耗时
NProgress.configure({ showSpinner: false }) // 进度条配置

//HTTPrequest拦截
axios.interceptors.request.use(req => {
  NProgress.start() // 进度条开始
  const isToken = (req.headers || {}).isToken === false;
  let token = store.getters.access_token;
  if (token && !isToken) {
    console.log(token);
    req.headers["Authorization"] = "Bearer " + token; // token
  } 
  return req
}, error => {
  return Promise.reject(error)
});
//HTTPresponse拦截
axios.interceptors.response.use(res => {
  NProgress.done() // 进度条结束
  const status = Number(res.status) || 200;
  const message = res.data.message || '未知错误';

  if (status === 401){
    store.dispatch('FedLogOut').then(() => router.push({ path: '/login' }));
  } 
  // 如果请求为非200否者默认统一处理
   if (status !== 200) {
    ElMessage({
      message: message,
      type: 'error'
    })
    return Promise.reject(new Error(message))
  }
  return res;
}, error => {
  NProgress.done();
  return Promise.reject(new Error(error));
})

export default axios;